from flask import Blueprint, render_template, request, flash
from models.entity.dict import Dict
import json
from utils.result import result

mod = Blueprint("core_dict", __name__, url_prefix="/core/dict", template_folder="templates", static_folder="static")


@mod.route('/get/', methods=['GET', 'POST'])
def get_dict():
    """得到字典列表中的字典项"""
    """传入的是字典类型中的id"""

    """
    {
        "id": 2
    }

    """
    if request.method == "POST":
        receive = request.data
        id = json.loads(receive.decode("utf-8"))["id"]
    else:
        id_t = request.args.get("id", type=int)
        id = id_t
    dicts = Dict.get_dicts_by_cate_id(cate_id=id)
    data = []
    for item in dicts:
        data.append(item.to_dict())
    return result(data=data)

@mod.route('/del/', methods=['POST'])
def del_dict_item():
    """删除字典项"""
    """
    {
    "id":2
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        id = int(dict['id'])
        if not Dict.get_dict_by_id(id):
            return result(success=0,error_code=-1,error_msg='没有该记录，请重新选择')
        dict1s = Dict.get_dict_by_id(id)
        if dict1s.delete():
            return result(success=1)
        else:
            return result(success=0,error_code=-2,error_msg='未知错误')


@mod.route('/add/', methods=['GET', 'POST'])
def add_dict():
    """这个函数的主要功能是添加字典项"""
    """
    {
    "name":"kkkk",
    "cate_id":4,
    "code":"dddddd",
    "dict_value":"ddddd",
    "pinyin":"kkk",
    "description":"ffffff",
    "status":1,
    "dis_order":3
    }
    """
    if request.method == 'POST':
        receive = request.data
        dict = json.loads(receive.decode('utf-8'))
        data = []
        dict_item = Dict()
        if Dict.get_dict_by_name(dict['name']):
            return result(success=0,error_code=-2,error_msg='名称已经存在')
        if Dict.get_dict_by_code(dict["code"]):
            return result(success=0,error_code=-2,error_msg='编码已存在')
        try:
            dict_item.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-1,error_msg=e)
        """
        if Dict.query.filter_by(code=code).first():
            tmp['success'] = 0
            tmp['error_code'] = -6
            tmp['error_msg'] = "Same Code is Exist"
            tmp['data'] = data
            return jsonify(tmp)
        #dict.code = code
        """
        if dict_item.save():
            return result(success=1)
        else:
            return result(success=0,error_msg='未知错误',error_code=-3)


@mod.route('/edit/', methods=['POST'])
def edit_dict():
    """这个函数的主要功能是编辑字典项"""
    """
    {
    "id":1,
    "cate_id":4,
    "name":"3ere3",
    "code":"rrrff",
    "pinyin":"jffj",
    "description":"ccccc",
    "dis_order":1,
    "dict_value":"55fff55",
    "status":3
    }
    """

    if request.method == 'POST':
        tmp = {}
        receive = request.data
        dict = json.loads(receive.decode("utf-8"))
        dict_item = Dict().get_entity_by_id(dict["id"])
        if dict['name'] != dict_item.name and Dict.get_dict_by_name(dict['name']) is not None:
            return result(success=0,error_code=-1,error_msg='名称已经存在')
        """
        if code != dict.code and Dict.query.filter_by(code=code).first() is not None:
            tmp['success'] = 0
            tmp['error_code'] = -9
            tmp['error_msg'] = "Same name exist"
            tmp['data'] = data
            return jsonify(tmp)
        dict.code = code
        """
        try:
            dict_item.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-2,error_msg=e)
        if dict_item.save():
            return result(success=1)
        else:
            return result(success=0,error_code=-2,error_msg='未知错误')


@mod.route('/get_dict_all/', methods=['GET', 'POST'])
def get_dict_item():
    """得到字典列表中的字典项"""
    """创建字典很不合理"""
    if request.method == 'POST':
        dicts = Dict().get_dict_all()
        data = []
        for item in dicts:
            data.append(item.to_dict())
        return result(data=data)


@mod.route("/search/",methods=["POST"])
def search_device_type():
    """
    查询button
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    if request.method == 'POST':
        receive = request.data
        data = json.loads(receive.decode("utf-8"))
        if 'query_word' in data:
            query_word = data['query_word']
        else:
            return result(success=0,error_msg='格式错误',error_code=-2)
        dicts = Dict.search(query_word)
        return result(data=dicts)